<?php

namespace App\Http\Requests\Admin;

use App\Http\Requests\FormRequest;
use Illuminate\Validation\Rule;

/**
 * @Author: dxf
 * @Date: 2021-07-16
 * @Time: 16:00
 */

/**
 * 数据字典
 */
class DictRequest extends FormRequest
{

    public function rules()
    {
        switch ($this->method()) {
            case 'GET':
            {
                return [
                    'keyword' => ['nullable', 'string'],
                ];
            }
            case 'POST':
            {
                $post_validate = [
                    'name'         => ['required', 'string', 'max:40'],
                    'value'        => ['required', 'array'],
                    'value.0.key'  => ['required'],
                    'value.0.item' => ['required', 'string'],
                    'value.*.item' => ['required_with:value.*.key', 'string'],
                ];
                if (strpos($this->path(), 'edit')) {
                    //官方文档上说明这种从路由输入值去验证唯一性的做法，容易sql注入，不建议这样使用
//                    $post_validate['slug'] = ['required', Rule::unique('dict', 'slug')->ignore($this->route('id')),'string', 'max:40'];
                    $post_validate['slug'] = ['required','string', 'max:40'];
                } else {
                    $post_validate['slug'] = ['required', 'unique:dict,slug,id', 'string', 'max:40'];
                }
                return $post_validate;
            }
            default:
            {
                return [

                ];
            }
        }
    }

    public function messages()
    {
        return [
            'name.required'              => '字典名称必须',
            'name.string'                => '字典名称必须是字符串',
            'name.max'                   => '字典名称不能超过:max个字符',
            'value.required'             => '字典值必须',
            'value.max'                  => '字典值不能超过:max个字符',
            'slug.required'              => '字典标识必须',
            'slug.max'                   => '字典标识不能超过:max个字符',
            'slug.string'                => '字典标识必须是字符串',
            'slug.unique'                => '字典标识已经存在',
            'value.0.key.required'       => '字典值json key必须',
            'value.0.item.required'      => '字典值json value必须',
            'value.0.item.string'        => '字典值json value必须是字符串',
            'value.*.item.required_with' => '字典值json value必须和key同时存在',
            'value.*.item.string'        => '字典值json value必须是字符串',
        ];
    }
}
